package cn.tedu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:jdbc.properties")
@MapperScan("cn.tedu.mapper")
public class MyBatisConfig {

    @Bean(initMethod = "init", destroyMethod = "close")
    public DataSource dataSource(
        @Value("${db.driver}")String driver,
        @Value("${db.url}")String url,
        @Value("${db.username}")String username,
        @Value("${db.password}")String password,
        @Value("${db.maxActive}")int maxActive,
        @Value("${db.initialSize}")int initialSize) {

            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(username);
            ds.setPassword(password);
            //最大链接数
            ds.setMaxActive(maxActive);
            //初始链接数量
            ds.setInitialSize(initialSize);
            return ds;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource,
                                               @Value("${mybatis.mapper.location}")
                                               Resource[] mapperLocations) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(mapperLocations);
        return bean.getObject();
    }
}
